﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Windows;

namespace XMM.Objects
{
    public class SupportedExtension : Object
    {
        public int ExtensionID { get; set; }

        public string Extension { get; set; }

        public int MediaType { get; set; }

        public SupportedExtension()
        {
            blankValues();
        }

        public SupportedExtension(int iExtensionID)
        {
            blankValues();
            ExtensionID = iExtensionID;
            Load(iExtensionID);
        }

        public void blankValues()
        {
            ExtensionID = 0;
            Extension = String.Empty;
            MediaType = 0;
        }

        public bool Load(int iExtensionID)
        {
            if(iExtensionID != 0)
            {
                try
                {
                    XMMDBDataContext dbConnection = new XMMDBDataContext();

                    var vExtension = (from extension in dbConnection.t_supported_extensions where extension.ID == iExtensionID select extension).Single();

                    if (vExtension != null && vExtension.ID != 0)
                    {
                        ExtensionID = vExtension.ID;
                        Extension = vExtension.Extension;
                        MediaType = vExtension.MediaType;

                        return true;
                    }
                }
                catch (SqlException ex)
                {
                    MessageBox.Show("Fehler beim Laden der Dateierweiterung '" + iExtensionID.ToString() + "': " + ex.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }

            return false;
        }

        public static List<Objects.SupportedExtension> getAllExtensions()
        {
            List<Objects.SupportedExtension> lExtensions = new List<SupportedExtension>();

            try
            {
                XMMDBDataContext dbConnection = new XMMDBDataContext();

                var vExtensionIDs = from extensionIDs in dbConnection.t_supported_extensions select extensionIDs.ID;

                if (vExtensionIDs != null && vExtensionIDs.Count() > 0)
                {
                    foreach (int iExtensionID in vExtensionIDs)
                    {
                        if (iExtensionID != 0)
                        {
                            lExtensions.Add(new SupportedExtension(iExtensionID));
                        }
                    }
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show("Fehler beim Abrufen der unterstützten Dateierweiterungen: " + ex.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            return lExtensions;
        }
    }
}
